package com.len.service;

import com.github.pagehelper.Page;
import com.len.controller.req.BaseReq;
import com.len.entity.DayDataEntity;
import com.len.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

@Service
public class DataService {

    @Resource
    private MongoTemplate mongoTemplate;

    @Resource
    private PageService pageService;

    public Page<DayDataEntity> getDayDataList(BaseReq req, Page<DayDataEntity> page) {
        Query query = new Query();
        query.skip((long) (page.getPageNum() - 1) *page.getPageSize());
        query.limit(page.getPageSize());

        Criteria criteria = new Criteria();
        if (StringUtils.isNotBlank(req.getBeginTime())&&StringUtils.isNotBlank(req.getEndTime())){
            criteria.and("time").gte(Integer.valueOf(DateUtil.date2TimeStamp(req.getBeginTime(),"yyyy-MM-dd"))).lt(Integer.parseInt(DateUtil.date2TimeStamp(req.getEndTime(),"yyyy-MM-dd"))+24*3600);
        }else if (StringUtils.isNotBlank(req.getBeginTime())){
            criteria.and("time").gte(Integer.valueOf(DateUtil.date2TimeStamp(req.getBeginTime(),"yyyy-MM-dd")));
        }else if (StringUtils.isNotBlank(req.getEndTime())){
            criteria.and("time").lt(Integer.parseInt(DateUtil.date2TimeStamp(req.getEndTime(),"yyyy-MM-dd"))+24*3600);
        }
        query.addCriteria(criteria);

        query.with(Sort.by(
                Sort.Order.desc("time")
        ));

        List<DayDataEntity> list = mongoTemplate.find(query, DayDataEntity.class);
        list.forEach(dayDataEntity -> {
            dayDataEntity.setRechargeAmountDecimal(new BigDecimal(dayDataEntity.getRechargeAmount()).divide(new BigDecimal(100),2,RoundingMode.HALF_DOWN));
            dayDataEntity.setNewUserRechargeAmountDecimal(new BigDecimal(dayDataEntity.getNewUserRechargeAmount()).divide(new BigDecimal(100),2, RoundingMode.HALF_DOWN));
        });
        long total = pageService.count(query, DayDataEntity.class);

        page.addAll(list);
        page.setTotal(total);
        return page;
    }


}
